package com.chengh.nami.common.utils;

import com.chengh.nami.common.domain.model.LoginUserEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * security工具类
 *
 * @author chengh
 */
@Slf4j
public class SecurityUtils {

    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 获取用户信息,只能获取用户的账号和ID以及存放在jwt的权限
     * 若要获取详细信息,请获取ID后查询数据库
     *
     * @return LoginUserEntity
     */
    public static LoginUserEntity getUserInfo() {
        Authentication authentication = getAuthentication();
        return (LoginUserEntity) authentication.getPrincipal();
    }


    /**
     * 获取用户名称
     *
     * @return 用户名
     */
    public static String getUsername() {
        return getUserInfo().getUsername();
    }

    /**
     * 判断密码是否相同
     * @param rawPassword 真实密码
     * @param encodedPassword 加密后字符
     * @return 是否相同
     */
    public static boolean matchesPassword(String rawPassword, String encodedPassword) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }

    /**
     * 生成BCryptPasswordEncoder密码
     *
     * @param password 密码
     * @return 加密字符串
     */
    public static String encryptPassword(String password) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.encode(password);
    }
}
